package com.xexun.gpstracker.baby.mytree;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.util.HttpUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;


import java.util.*;


/**
 * Created by Administrator on 2016/11/23.
 */
public class MyTreeListAdapter extends BaseAdapter {

    private String TAG = MyTreeListAdapter.class.getSimpleName();
//    static final String TREEURL = "http://120.25.75.101:8080/terminal/getDataNodesById";
    static final String TREEURL = Constants.baseUrl+"terminal/getDataNodesById";

    protected Context mContext;


    /**
     * 存储所有可见的Node
     */
    public List<MyNode> mNodes;

    /**
     * 存储所有的Node
     */
    protected List<MyNode> mAllNodes;


    protected LayoutInflater mInflater;

    protected ListView myTree;


    /**
     * 点击的回调接口
     */
    private OnTreeNodeClickListener onTreeNodeClickListener;


    public interface OnTreeNodeClickListener
    {
        void onClick(MyNode node,int position);
    }


    public void setOnTreeNodeClickListener(OnTreeNodeClickListener onTreeNodeClickListener){
        this.onTreeNodeClickListener = onTreeNodeClickListener;

    }


    public MyTreeListAdapter(ListView mTree,Context context, List<MyNode> datas) throws IllegalArgumentException,
            IllegalAccessException
    {
        mContext = context;
        mInflater = LayoutInflater.from(context);
        mAllNodes = datas;
        mNodes = createTempData(mAllNodes);
        myTree = mTree;
        myTree.setOnItemClickListener(clickListener);

    }



    private MyNode selectParentNode;

    private int selectPosition;



    private static long lastClickTime = 0;
    private final static int SPACE_TIME = 500;

    private AdapterView.OnItemClickListener clickListener = new AdapterView.OnItemClickListener() {


        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//先修改数据源

            Log.i(TAG ,"点击ListView头");
            //防止重复点击
//            long currentTime = System.currentTimeMillis();
//            if (currentTime - lastClickTime < SPACE_TIME) {
//                lastClickTime = currentTime;
//               return;
//            }
//
//            lastClickTime = currentTime;


          MyNode node = mNodes.get(position);

            selectParentNode = node;
            selectPosition = position;

            if(!node.getHasChildren()){

                if(node.getNodeId().contains("USER")){

                    return;
                }


                if (onTreeNodeClickListener != null)
                {
                    onTreeNodeClickListener.onClick(node,position);
                }

                return;
            }


           if(node.getGet()){
               Log.d(TAG, "已经获取过设备列表,直接展示");
               updateData();
               return;
           }
            node.setGet(true);


           //获取网络数据

            JSONObject jsonObj = new JSONObject();
            try {
                jsonObj.put("nodeId",node.getNodeId()) ;
                Log.d(TAG, "本机nodeID:"+node.getNodeId());
            } catch (JSONException e) {
                e.printStackTrace();
            }


            HttpUtil.post(TREEURL, jsonObj, new Callback.ProgressCallback<JSONObject>() {
                @Override
                public void onWaiting() {

                }

                @Override
                public void onStarted() {

                }

                @Override
                public void onLoading(long total, long current, boolean isDownloading) {

                }

                @Override
                public void onSuccess(JSONObject result) {


                    JSONArray jsonArray = null;
                    MyNode parentNode = mNodes.get(position);

                    Log.i(TAG ,result.toString());

                    try {
                        jsonArray = result.getJSONArray("body");
                        if(jsonArray == null){


                            Log.d(TAG, "获取设备列表失败");
                            return;
                        }

                        List<MyNode> list = new ArrayList<MyNode>();


                        for(int i = 0 ; i<jsonArray.length() ;i++){
                            JSONObject obj = jsonArray.getJSONObject(i);
                            MyNode node = new MyNode(parentNode.getNodeId(),obj.getString("id"), obj.getString("name"),parentNode.getDepth() + 1,false,obj.getBoolean("isParent"),"http://120.25.75.101:8080"+obj.optString("portrait"));
                            mAllNodes.add(node);
                        }

                        parentNode.setGet(true);

                        updateData();


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });




        }
    };



    //更新数据
    private  void updateData(){


        int startPosition = selectPosition + 1;
        int endPosition = startPosition;


        Boolean expand = false;



//        Log.d(TAG, "mAllNodes"+ mAllNodes.toString());
        Gson gson = new Gson();
        String str = gson.toJson(mAllNodes);
        Log.d(TAG, "mAllNodes"+ str);

        for(MyNode node : mAllNodes){
            if(node.getParentId().equals(selectParentNode.getNodeId())){
                node.setExpand(!node.getExpand());
                if(node.getExpand()){
                    mNodes.add(endPosition,node);
                    expand = true;
                    endPosition++;
                }else {
                    expand = false;
                    endPosition = removeAllNodesAtParentNode(selectParentNode);
                    break;
                }
            }
        }


        //刷新界面
        notifyDataSetChanged();

    }


    /**
     * 删除该父节点下的所有子节点(包括孙子节点)
     * @param parentNode 父节点
     * @return 该父节点下一个相邻的统一级别的节点的位置
     */
  private  int removeAllNodesAtParentNode(MyNode parentNode){


      int startPostition = mNodes.indexOf(parentNode);
      int endPostition = startPostition;


      for(int i = startPostition+1;i<mNodes.size();i++){
          MyNode node = mNodes.get(i);
          endPostition++;

          if(node.getDepth() <= parentNode.getDepth()){
              break;
          }
          if(endPostition == mNodes.size() - 1 ){
              endPostition++;
              node.setExpand(false);
              break;
          }
          node.setExpand(false);
      }


      if(endPostition > startPostition){

          for(int j = endPostition - 1 ; j > startPostition ; j--){
             mNodes.remove(j);
          }


      }

      return endPostition;
  }








    /**
     * 初始化数据源
     * @return
     */

    private List<MyNode> createTempData (List<MyNode> list){

        List<MyNode> tempList = new ArrayList<MyNode>();

        for(MyNode node : list){

          if(node.getExpand()){
              tempList.add(node);
          }
        }

        return tempList;
    }






    @Override
    public int getCount() {
        return mNodes.size();
    }

    @Override
    public Object getItem(int position) {
        return mNodes.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    //在外面先定义，ViewHolder静态类
    static class ViewHolder
    {

        public TextView text;

    }





    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView == null)
        {
            convertView = mInflater.inflate(R.layout.list_item, parent, false);
            holder = new ViewHolder();
            holder.text = (TextView) convertView
                    .findViewById(R.id.id_treenode_label);
            convertView.setTag(holder);
        }else
        {
            holder = (ViewHolder) convertView.getTag();
        }

            MyNode node = mNodes.get(position);

           // 设置内边距
             convertView.setPadding(node.getDepth() * 30, 3, 3, 3);


            holder = (ViewHolder)convertView.getTag();

            String textStr = node.getName();

            holder.text.setText((node.getHasChildren() || textStr.length()< 8 || node.getNodeId().contains("USER") )?  textStr : textStr.substring(textStr.length() - 7) );


        return convertView;
    }







}
